﻿<!DOCTYPE html>
<html>
    <head>
        <title>My Trips 2</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&amp;sensor=false&amp;key=AIzaSyBU7QKmIDolsy8AgZoP57vf9EhY-Eore0w" type="text/javascript"></script>
        <script type="text/javascript">
            var route;
            var map;
            var directionsDisplay;
            var directionsService;
             google.maps.event.addDomListener(window, 'load', initialize);
             
             function initialize(){
                directionsDisplay = new google.maps.DirectionsRenderer();
                directionsDisplay.setPanel(document.getElementById('directions-panel'));
                directionsService = new google.maps.DirectionsService();

                var mapOptions = {
                    zoom: 15,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                map = new google.maps.Map(document.getElementById('map-panel'), mapOptions);
                directionsDisplay.setMap(map);

                google.maps.event.addDomListener(directionsDisplay, "directions_changed", function() {
                    RedrawRoutesSchdule();
                });
             }
             
            function go_click(){
                var From = document.getElementById('locationS').value;
                var To = document.getElementById('locationE').value;
                var w =new Array();
                for(var i=1;i<=8;i++){
                    var tmp=document.getElementById('location' + i.toString().trim()).value;
                    if(tmp.trim()!==''){
                        w.push( tmp);
                    }
                }
                var postParas="myMap.html?AutoStart";
                postParas += "&From=" + From;
                postParas += "&To=" + To;
                for(var i=0; i < w.length ;i++){
                    postParas += "&WayPoint=" + encodeURIComponent(w[i]);
                }
                document.getElementById('debuginfo').innerHTML = postParas ;
                
                //window.location.replace(postParas);
                //window.location.assign(postParas);
                window.open( postParas , 'Test');
                
            }
            
            function plan_click(){
                document.getElementById('debuginfo').innerHTML = "plan_click" ;
                calcRoute();
            }
            
            /* 路徑規劃 */
            function calcRoute() {
                document.getElementById('debuginfo').innerHTML = "calcRoute" ;
                var selectedMode = 'DRIVING';
                var start = document.getElementById('locationS').value;
                var end = document.getElementById('locationE').value;
                var wayps = new Array();
                for(var i=1; i<= 8 ;i++ ){
                    var wayp = document.getElementById('location' + i.toString().trim() ).value;
                    if(wayp!==''){
                        wayps.push({location:wayp, stopover:true});
                    }
                }
                var request = {
                    origin: start,
                    destination: end,
                    travelMode: google.maps.DirectionsTravelMode[selectedMode],
                    waypoints: wayps
                };
                document.getElementById('debuginfo').innerHTML = "calcRoute2" ;
                directionsService.route(request, function(response, status) {
                    document.getElementById('debuginfo').innerHTML = "calcRoute callbackfunc" ;
                    if (status === google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(response);
                    }
                });
            }
             function RedrawRoutesSchdule(){
                 document.getElementById('debuginfo').innerHTML = "RedrawRoutesSchdule in" ;
                 var inpanel = ""; 
                 var route = directionsDisplay.getDirections().routes[0];
                 var traveltime=new Date();
                 traveltime=new Date( traveltime.toISOString().substr(0,10) + " 08:00:00") ;
                 
                 inpanel += "<table border=\"1\">";
                 inpanel += "<tr>";
                 inpanel += "<td>預定</td><td>時間</td><td>行程(分)</td><td>地點／活動說明</td>";
                 inpanel += "</tr>";

                 inpanel += "<tr>";
                 /* inpanel += "<td>" + "<input type=\"checkbox\" id=\"chk0" +  "\" disabled=\"true\" checked=\"true\"/>" + "</td>"; */
                 inpanel += "<td>" + "" + "</td>";
                 inpanel += "<td>" + "<select class=\"arrivetime\" id=\"arrivetime0\" onchange=\"recaclTimeplan()\">" + getArriveTimeSelect(traveltime.toTimeString(),traveltime.toTimeString()) + "</select>  出發 "  + "</td>" + "<td />" + "<td>"+ "0. " +  route.legs[0].start_address + "</td>"; 
                 inpanel += "</tr>";
                 for(var l =0 ; l < route.legs.length; l++){
                    if(l!==0){
                        inpanel += "<tr>";
                        inpanel += "<td/><td>預計停留</td>" ;
                        inpanel += "<td>" + getStaySelect(l.toString().trim(),0) + "分</td>"; 
                        inpanel += "<td></td>" ;
                        inpanel += "</tr>";
                    }

                    inpanel += "<tr>";
                    inpanel += "<td/><td> 前往下一點 </td>" ;
                    inpanel += "<td>" +Math.ceil(route.legs[l].duration.value/60) + " 分</td>"; 
                    inpanel += "<td></td>" ;
                    inpanel += "</tr>";

                    inpanel += "<tr>";
                    inpanel += "<td/><td>" + "<span id=\"idletimedesc" + l.toString().trim() + "\" ></span>" + "</td>"  ;
                    inpanel += "<td>" + "<span id=\"idletime" + l.toString().trim() + "\" ></span>" + "</td>"; 
                    inpanel += "<td></td>" ;
                    inpanel += "</tr>";

                    traveltime.setTime(traveltime.getTime() + (Math.ceil(route.legs[l].duration.value/60) * 60 * 1000));

                    inpanel += "<tr>";
                    inpanel += "<td>" + "<input type=\"checkbox\" id=\"chk" + (l+1).toString() +  "\"  />" + "</td>";
                    inpanel += "<td>" + "<select class=\"arrivetime\" id=\"arrivetime" + (l+1).toString().trim() + "\" onchange=\"recaclTimeplan()\">" + getArriveTimeSelect(traveltime.toTimeString(),traveltime.toTimeString()) + "</select>  抵達 "  + "</td>" + "<td />" + "<td>"+ (l+1).toString() + ". " +  route.legs[l].end_address + "</td>"; 
                    inpanel += "</tr>";
                 }
                 inpanel += "</table>";
                 document.getElementById('route-panel').innerHTML=inpanel;
             }
             
             function recaclTimeplan(){
                 var departuretime = document.getElementById('arrivetime0');
                 var traveltime=GetNewTodayTime(departuretime.value); 
                 var route = directionsDisplay.getDirections().routes[0];
                 var arrivetime_this;
                 var seltime;
                 for(var l =0 ; l <= route.legs.length; l++){
                    arrivetime_this=document.getElementById('arrivetime' + l.toString().trim());
                     seltime = arrivetime_this.value;
                     if(l!==0){
                         var chk_this = document.getElementById('chk' + l.toString().trim());
                         var idletime = document.getElementById('idletime' + (l-1).toString().trim());
                         var idletimedesc = document.getElementById('idletimedesc' + (l-1).toString().trim());
                         
                         if (chk_this.checked){
                             arrivetime_this.innerHTML = getArriveTimeSelect(traveltime.toTimeString(),seltime);
                             var presettime = GetNewTodayTime(seltime);
                             var idleminutes=Math.round((presettime.getTime()-traveltime.getTime())/1000/60);
                             if(idleminutes<=15 && idleminutes >= 0){
                                 idletime.innerHTML="";
                                 idletimedesc.innerHTML="";
                             }else{
                                 document.getElementById('debuginfo').innerHTML = "traveltime=" + traveltime.toISOString()  + ", seltime = " + presettime.toISOString() ;
                                 idletime.innerHTML= idleminutes.toString() + " 分";
                                 idletimedesc.innerHTML= ( idleminutes >=0 ? "空閒":"時間不足" );
                                 idletime.style.color = (idleminutes >=0 ? 'blue': 'red');
                                 idletimedesc.style.color = (idleminutes >=0 ? 'blue': 'red');
                             }
                             traveltime=GetNewTodayTime(seltime);
                         }else{
                             idletime.innerHTML="";
                             idletimedesc.innerHTML="";
                            arrivetime_this.innerHTML = getArriveTimeSelect(traveltime.toTimeString(),traveltime.toTimeString());
                        }
                        if(l!== route.legs.length){
                            var staytime =  document.getElementById('staytime' + l.toString().trim());
                            traveltime.setTime(traveltime.getTime() + staytime.value * 60 * 1000);
                        }
                     }
                     if(l!== route.legs.length){traveltime.setTime(traveltime.getTime() + (Math.ceil(route.legs[l].duration.value/60) * 60 * 1000));}
                 }
             }

             function getArriveTimeSelect(eta,seltime){
                 var inpanel="";
                 for(var t=0;t<24;t++){
                    var st10= t.toString().Lfill(2,"0") + ":00:00";
                    var st15= t.toString().Lfill(2,"0") + ":30:00";
                    var st20= (t+1).toString().Lfill(2,"0") + ":00:00";
                    inpanel += "<option value=\"" + st10 + "\"" + (st10===seltime? " SELECTED ":"") + ">" + t.toString().Lfill(2,"0") + ":00</option>";
                    if(st10 < eta && eta < st15){
                        inpanel += "<option value=\"" + eta + "\"" + (eta===seltime? " SELECTED ":"") + ">" + eta.substring(0,5) + "</option>";
                    }
                    inpanel += "<option value=\"" + st15 + "\"" + (st15===seltime? " SELECTED ":"") + ">" + t.toString().Lfill(2,"0") + ":30</option>";
                    if(st15 < eta && eta < st20){
                        inpanel += "<option value=\"" + eta + "\"" + (eta===seltime? " SELECTED ":"") + ">" + eta.substring(0,5) + "</option>";
                    }
                 }
                 return inpanel;
             }
    
             function getStaySelect(idstr,selectedvalue){
                 var retstr ="<select id=\"staytime" + idstr + "\" onchange=\"recaclTimeplan()\">";
                 var period=30;
                 if (selectedvalue===undefined){selectedvalue=0;}
                 for(var t=0;t<24;t++){
                     var vstr=(t * period).toString().trim();
                    retstr += "<option value=\"" + vstr + "\"" + ((t * period)===selectedvalue? " SELECTED ":"") + ">" + vstr + "</option>";
                 }
                 retstr += "</select>";
                 return retstr;
             }
    
            String.prototype.Lfill = function(len,fills) {
                var newstr=(fills.repeat(len) + this);
                return (newstr.substr(newstr.length-len,len));
            };
            String.prototype.repeat = function(times) {
               return (new Array(times + 1)).join(this);
            };
            function GetNewTodayTime(timestr){
                var _today = new Date();
                var _newdatetime = new Date(_today.getYear(),_today.getMonth(),_today.getDate(),timestr.substr(0,2),timestr.substr(3,2),0,0);
                return _newdatetime;
            }
        </script>
        <style type="text/css">
            html { height: 100%; }
            body { height: 100%; margin: 0; padding: 0; }
            #panels  { height: 100%; float: left; width: 35%; overflow: auto;  border: 1px solid gray;}
            #panels2 {height:100%; float: right; width: 64%; overflow:auto; border: 1px solid gray;}
            
            #SE-panel { height: 49%; width: 99%; border: 1px solid gray;}
            #directions-panel { height: 49%; width: 99%; overflow: auto;  border: 1px solid gray;}
            
            #route-panel {height:49%; width: 100%; overflow:auto; border: 1px solid gray;}
            #map-panel {height:49%; width: 100%; overflow:auto; border: 1px solid gray;}
            [type="text"] {width: 90%;}
            table {height:auto; width: 100%; border: 1px solid gray; }
            .arrivetime {color:blue;}
        </style>
    </head>
    <body>
        <div id="panels">
            <div id="SE-panel">
                <form>
                    <h3>輸入地點</h3><br>
                    起點: <input type="text" id="locationS" /><br>
                    點 1: <input type="text" id="location1" /><br>
                    點 2: <input type="text" id="location2" /><br>
                    點 3: <input type="text" id="location3" value=""/><br>
                    點 4: <input type="text" id="location4" value=""/><br>
                    點 5: <input type="text" id="location5" value=""/><br>
                    點 6: <input type="text" id="location6" /><br>
                    點 7: <input type="text" id="location7" /><br>
                    點 8: <input type="text" id="location8" /><br>
                    終點: <input type="text" id="locationE" value=""/><br>
                    <input type="button" id="plan" onclick="plan_click();" value="行程規劃" />
                    <input type="button" id="go" onclick="go_click();" value="模擬駕駛" /><br>
                    <label id="debuginfo"> debug info</label>
                </form>
            </div>
            <form><div id="directions-panel"></div></form>
        </div>
        <div id="panels2">
            <div id="route-panel"></div>
            <div id="map-panel"></div>
        </div>
    </body>
</html>